package cn.tannn.ops.logs.controller.dto;


import cn.tannn.ip2region.sdk.IpRegionUtil;
import cn.tannn.ip2region.sdk.UserAgentUtil;
import cn.tannn.jdevelops.utils.http.IpUtil;
import cn.tannn.jdevelops.utils.jwt.core.JwtService;
import cn.tannn.jdevelops.utils.time.TimeUtil;
import cn.tannn.ops.customer.constant.LoginType;
import cn.tannn.ops.customer.entity.Customer;
import cn.tannn.ops.logs.entity.LoginLog;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

/**
 * 登录日志记录
 *
 * @author <a href="https://tannn.cn/">tan</a>
 * @date 2024/4/8 11:28
 */
@Getter
@Setter
@ToString
@Slf4j
public class LoginLogRecord {

    /**
     * 登录者
     */
    private Customer customer;
    /**
     * 登录token
     */
    private String token;

    /**
     * 请求头
     */
    private HttpServletRequest request;

    /**
     * 登录状态：0[失败],1[成功]
     */
    private Integer status;

    /**
     * 备注
     */
    private String description;

    /**
     * 登录类型
     *
     * @see LoginType
     */
    private String type;


    public LoginLog recordStorage(){
        LoginLog recordLog = new LoginLog();
        recordLog.setUserAgent(UserAgentUtil.parseStr(request));
        String poxyIpEnhance = IpUtil.getPoxyIpEnhance(request);
        recordLog.setIpAddress(poxyIpEnhance);
        recordLog.setIpRegion(IpRegionUtil.getIpRegion(poxyIpEnhance));
        recordLog.setLoginTime(TimeUtil.thisDefNow());
        if (null != customer) {
            recordLog.setUserName(customer.getName());
            recordLog.setLoginName(customer.getLoginName());
            recordLog.setUserId(customer.getId());
        }
        recordLog.setStatus(status);
        recordLog.setToken(token);
        String tokenPlatform = "";
        if (token != null) {
            try {
                tokenPlatform = String.join(",", JwtService
                        .getPlatformConstantExpires(token));
            } catch (Exception e) {
                log.warn("token platform 获取失败", e);
            }
        }
        recordLog.setPlatform(tokenPlatform);
        recordLog.setType(type);
        recordLog.setDescription(description);
        return recordLog;
    }

}
